<template>
  <AppNavBar> 订单预览 </AppNavBar>
  <div class="fill"></div>
  <div class="address-box" @click="$router.push('/address')" v-if="address">
    <div class="address-info">
      <p>{{ address.name }} {{ address.phone }}</p>
      <p><i class="iconfont icon-dizhiguanli"></i>{{ address.address }}</p>
    </div>
    <span>
      <i class="iconfont icon-you"></i>
    </span>
  </div>
  <!-- 分割线 -->
  <Divider
    :style="{ color: '#42b983', borderColor: '#1989fa', padding: '0 16px' }"
    >订单列表</Divider
  >

  <card
    v-for="order in orders"
    :key="order.id"
    :num="order.num"
    :price="order.goods.price"
    :title="order.goods.title"
    :thumb="order.goods.cover_url"
  />
  <submit-bar
    :price="totalMoney * 100"
    button-text="提交订单"
    @submit="onSubmit"
  >
    商品金额
  </submit-bar>

  <popup
    v-model:show="showPay"
    closeable
    position="bottom"
    :style="{ height: '30%' }"
  />
</template>

<script>
import { ref, reactive } from 'vue'
import AppNavBar from '@/components/library/AppNavBar.vue'
import { SubmitBar, Divider, Card, Toast, Popup } from 'vant'
import { commitOrder, previewOrder, getPayCode, getPayStatus } from '@/api/order'
export default {
  name: 'CreateOrder',
  components: { AppNavBar, SubmitBar, Divider, Card, Popup },
  setup () {
    const orders = ref([])
    const address = ref(null)
    const totalMoney = ref(0)
    const showPay = ref(false)
    const pay = reactive({
      aliCode: '',
      weChatCode: ''
    })
    // 返回的就是购物车中勾选的商品
    previewOrder().then(res => {
      orders.value = res.data.carts
      totalMoney.value = res.data.carts.reduce((p, c) => p + c.goods.price * c.num, 0)
      address.value = res.data.address.find(address => address.is_default === 1)
    })

    // 提交订单
    const onSubmit = () => {
      // 生成订单
      commitOrder(address.value.id).then(res => {
        if (res.status === 200) {
          // 获取二维码的id
          const orderId = res.data.order_no
          Toast.success('提交成功！')
          getPayCode(orderId, 'aliyun').then(res => {
            console.log(res)
          })
          getPayStatus(orderId).then(res => {
            console.log(res)
          })
        }
      })
    }
    return {
      orders,
      address,
      onSubmit,
      totalMoney,
      pay,
      showPay
    }
  }
}
</script>

<style scoped lang='less'>
.van-submit-bar {
  bottom: 70px;
}
.fill {
  height: 53px;
}
.address-box {
  color: #000;
  display: flex;
  padding: 0 10px;
  justify-content: center;
  align-items: center;
  height: 80px;
  border-bottom: 1px solid #eee;
  .address-info {
    flex: 1;
  }
  p {
    padding: 5px 5px;
    vertical-align: center;
  }
}
</style>
